package com.autumn.platform.auth.web.access;

import java.util.List;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import com.autumn.platform.auth.core.access.IPermission;
import com.autumn.platform.core.logger.Logs;
import com.autumn.platform.web.request.IWebRequest;

public class AllowPathMatcherPermissionMapping extends AbstractWebPermissionMapping {

    private final PathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 匹配的URL模式
     */
    private List<String> urlPatterns;

    @Override
    protected IPermission lookup(IWebRequest request) {
        if (this.isMatcher(request.getRequestUrl())) {
            return IPermission.ANY;
        }
        return null;
    }

    /**
     * 是否匹配
     * 
     * @param url 目标URL
     * @return 是否匹配
     */
    private boolean isMatcher(String url) {
        List<String> urlPatterns = getUrlPatterns();
        if (null != urlPatterns && !urlPatterns.isEmpty()) {
            for (String pattern : urlPatterns) {
                if (pathMatcher.match(pattern, url)) {
                    Logs.debug("Request url [" + url + "] to match the ignored url pattern [" + pattern + "], so authentication is passed ");
                    return true;
                }
            }
        }
        return false;
    }

    public List<String> getUrlPatterns() {
        return urlPatterns;
    }

    public void setUrlPatterns(List<String> urlPatterns) {
        this.urlPatterns = urlPatterns;
    }
}
